package cliente;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;
import java.io.InputStream;
import java.net.URL;

import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.JTextPane;

import at.jta.RegistryErrorException;

public class Cliente extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTextField txtip;
	private JTextPane txtinfo;
	Identificador idEquipo = new Identificador();
	
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Cliente frame = new Cliente();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public Cliente() {
		setBounds(100, 100, 828, 426);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[]{275, 73, 86, 93, 0};
		gridBagLayout.rowHeights = new int[]{23, 0, 0, 0};
		gridBagLayout.columnWeights = new double[]{1.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
		gridBagLayout.rowWeights = new double[]{0.0, 0.0, 1.0, Double.MIN_VALUE};
		getContentPane().setLayout(gridBagLayout);
		
		JButton btnconectar = new JButton("Comunicarse");
		btnconectar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				comunicarse();
			}
		});
		
		JLabel lblNewLabel = new JLabel("IP del servidor:");
		GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
		gbc_lblNewLabel.anchor = GridBagConstraints.WEST;
		gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5);
		gbc_lblNewLabel.gridx = 1;
		gbc_lblNewLabel.gridy = 0;
		getContentPane().add(lblNewLabel, gbc_lblNewLabel);
		
		txtip = new JTextField();
		GridBagConstraints gbc_txtip = new GridBagConstraints();
		gbc_txtip.anchor = GridBagConstraints.WEST;
		gbc_txtip.insets = new Insets(0, 0, 5, 5);
		gbc_txtip.gridx = 2;
		gbc_txtip.gridy = 0;
		getContentPane().add(txtip, gbc_txtip);
		txtip.setColumns(10);
		GridBagConstraints gbc_btnconectar = new GridBagConstraints();
		gbc_btnconectar.insets = new Insets(0, 0, 5, 0);
		gbc_btnconectar.anchor = GridBagConstraints.NORTHWEST;
		gbc_btnconectar.gridx = 3;
		gbc_btnconectar.gridy = 0;
		getContentPane().add(btnconectar, gbc_btnconectar);
		
		txtinfo = new JTextPane();
		GridBagConstraints gbc_txtinfo = new GridBagConstraints();
		gbc_txtinfo.gridwidth = 4;
		gbc_txtinfo.insets = new Insets(0, 0, 0, 5);
		gbc_txtinfo.fill = GridBagConstraints.BOTH;
		gbc_txtinfo.gridx = 0;
		gbc_txtinfo.gridy = 2;
		getContentPane().add(txtinfo, gbc_txtinfo);

	}
	void ponertexto(String msg){
		txtinfo.setText(txtinfo.getText() + "\n" + msg);
	}
	protected void comunicarse() {
		String id ;
		try {
			id = idEquipo.capturarIdMaquina();
		} catch (RegistryErrorException e) {
			id="null";
		}
		ponertexto("Identificador de este equipo: "+id);
		
		ponertexto("Tratando de comunicar con "+txtip.getText());
		ponertexto("Espere..");
		String respuesta;
		String  dest;
		dest = "http://"+txtip.getText()+":8080/SERVER/inicio.jsp?param="+id;
		ponertexto("llamando a "+dest);
		respuesta = identificar(dest);
		ponertexto("Respuesta de: "+txtip.getText()+" = "+ respuesta);
		if (respuesta.equals("existe"))
		{
			ponertexto("EL EQUIPO YA HA SIDO REGISTRADO");
		}
		if (respuesta.equals("no existe"))
		{
			ponertexto("Tratando de guardar datos del cliente en el servidor..");
			dest = "http://"+txtip.getText()+":8080/SERVER/inicio.jsp?param=insertar&id="+id+"&nombre=nombre&numero=numero&ubicacion=ubicacion&estado=1";
			ponertexto("llamando a "+dest);
			respuesta = identificar(dest);
			ponertexto("Respuesta de: "+txtip.getText()+" = "+ respuesta);
		}
		
		ponertexto("Terminado..");
	}

	public String identificar(String destino){
		try
	      {
	    	
		    URL          url = new URL(destino);
		    Object       obj = url.getContent();
		    InputStream  resp = (InputStream)obj;
		    byte[]       b = new byte[256];
		    int          n = resp.read(b);
		  		    String cadena = "";
		    while (n != -1)
		    {
		      cadena = cadena + new String(b, 0, n);
		       n = resp.read(b);
		      }
		      return cadena.trim();
		      } catch(Exception ex){	
		    	  return "error";
		      }
	}

}
